package com.example.servicemap.remote;

import com.example.internalcommon.constant.AmapConfigConstants;
import com.example.internalcommon.dto.ResponseResult;
import com.example.internalcommon.request.PointDTO;
import com.example.internalcommon.request.PointRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

/**
 * @Author lyra
 * @Date 2023/4/19 8:45
 **/
@Service
public class PointClient {

    @Value("${amap.key}")
    private String amapkey;

    @Value("${amap.sid}")
    private String amapsid;

    @Autowired
    private RestTemplate restTemplate;


    public ResponseResult upload(PointRequest pointRequest){
        // 拼装请求的url
        StringBuilder url = new StringBuilder();
        url.append(AmapConfigConstants.POINT_UPLOAD);
        url.append("?");
        url.append("key="+amapkey);
        url.append("&");
        url.append("sid="+amapsid);
        url.append("&");
        url.append("tid="+pointRequest.getTid());
        url.append("&");
        url.append("trid="+pointRequest.getTrid());
        url.append("&");
        url.append("points=");
        // 使用URL编码拼接URL
        url.append("%5B"); // [ 的 编码
        PointDTO[] points = pointRequest.getPoints();
        // 通过URL编码对url进行修改
        for (PointDTO p : points){
            url.append("%7B");
            String locatetime = p.getLocatetime();
            String location = p.getLocation();
            url.append("%22location%22");
            url.append("%3A");
            url.append("%22"+location+"%22");
            url.append("%2C");
            url.append("%22locatetime%22");
            url.append("%3A");
            url.append(locatetime);
            url.append("%7D");
        }
        url.append("%5D");
        System.out.println("高德地图请求 "+url.toString());

        // URI.create(url.toString()) 解决URI编码问题
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(URI.create(url.toString()), null, String.class);

        System.out.println("高德地图响应"+ stringResponseEntity.getBody());

        return ResponseResult.success("");
    }
}
